﻿using System;
using System.Linq;
using Complaint.Models.Dtos;
using Complaint.Models.Dtos.Enums;

namespace Complaint.Repositories
{
    public class UserRepository : BaseRepository<User>, IRepository<User>
    {
        #region IRepository<User> Members

        public void Create(User dto)
        {
            ObjectContext.AddToUser(dto);
            Update(dto);
        }

        public IQueryable<User> FindAll()
        {
            return ObjectContext.User;
        }

        public User FindById(int id)
        {
            return FindAll().FirstOrDefault(u => u.UserID == id);
        }

        public IQueryable<User> FindByName(string name)
        {
            return from user in FindAll()
                   where user.DisplayName == name || user.Email == name
                   select user;
        }

        #endregion

        public IQueryable<User> FindAll(LoadUser loadOption)
        {
            var result = LoadResult(FindAll(), (int)loadOption);
            return result;
        }

        public User FindById(int id, LoadUser loadOption)
        {
            var result = ObjectContext.User.Where(u => u.UserID == id);
            return LoadResult(result, (int)loadOption).FirstOrDefault();
        }

        public IQueryable<User> FindByName(string name, LoadUser loadOption)
        {
            var result = LoadResult(FindByName(name), (int)loadOption);
            return result;
        }

        public IQueryable<User> FindByEmail(string email, LoadUser loadOption)
        {
            var result = ObjectContext.User.Where(u => u.Email.Equals(email, StringComparison.InvariantCultureIgnoreCase));
            return LoadResult(result, (int)loadOption);
        }

        #region override
        protected override IQueryable<User> LoadResult(IQueryable<User> result, int loadOption)
        {
            if ((loadOption & (int)LoadUser.PasswordQuestion) == (int)LoadUser.PasswordQuestion)
            {
                result = result.Include("PasswordQuestion");
            }
            if ((loadOption & (int)LoadUser.Complaint) == (int)LoadUser.Complaint)
            {
                result = result.Include("Complaint");
            }
            return result;
        }
        #endregion
    }
}